<html><head><meta charset="utf-8"><title>36 从容不迫：重写锁的设计结构和细节 -慕课专栏</title>
			<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
			<meta name="renderer" content="webkit">
			<meta property="qc:admins" content="77103107776157736375">
			<meta property="wb:webmaster" content="c4f857219bfae3cb">
			<meta http-equiv="Access-Control-Allow-Origin" content="*">
			<meta http-equiv="Cache-Control" content="no-transform ">
			<meta http-equiv="Cache-Control" content="no-siteapp">
			<link rel="apple-touch-icon" sizes="76x76" href="https://www.imooc.com/static/img/common/touch-icon-ipad.png">
			<link rel="apple-touch-icon" sizes="120x120" href="https://www.imooc.com/static/img/common/touch-icon-iphone-retina.png">
			<link rel="apple-touch-icon" sizes="152x152" href="https://www.imooc.com/static/img/common/touch-icon-ipad-retina.png">
			<link href="https://moco.imooc.com/captcha/style/captcha.min.css" rel="stylesheet">
			<link rel="stylesheet" href="https://www.imooc.com/static/moco/v1.0/dist/css/moco.min.css?t=201907021539" type="text/css">
			<link rel="stylesheet" href="https://www.imooc.com/static/lib/swiper/swiper-3.4.2.min.css?t=201907021539">
			<link rel="stylesheet" href="https://static.mukewang.com/static/css/??base.css,common/common-less.css?t=2.5,column/zhuanlanChapter-less.css?t=2.5,course/inc/course_tipoff-less.css?t=2.5?v=201907051055" type="text/css">
			<link charset="utf-8" rel="stylesheet" href="https://www.imooc.com/static/lib/ueditor/themes/imooc/css/ueditor.css?v=201907021539"><link rel="stylesheet" href="https://www.imooc.com/static/lib/baiduShare/api/css/share_style0_16.css?v=6aba13f0.css"></head>
			<body><div id="main">


<div class="main-con hide-menu">
    <!-- 左侧菜单 & 索引 -->
    
    <div class="right-content" style="padding-left: 0px;">
        <div class="container clearfix" id="top" style="width: 1134px; display: block;">
            
            
            <div class="center_con js-center_con l" style="width: 1134px;">
                <div class="article-con">
                                            <!-- 买过的阅读 -->
                        

                    
                    <div class="art-title" style="margin-top: 0px;">
                        36 从容不迫：重写锁的设计结构和细节 
                    </div>
                    <div class="art-info clearfix">
                        
                        <span class="l">
                            更新时间：2019-11-15 11:04:05
                        </span>
                    </div>
                    <div class="art-top">
                                                <img src="https://img1.mukewang.com/5dce12d3000138f106400359.jpg" alt="">
                                                                        <div class="famous-word-box">
                            <img src="https://www.imooc.com/static/img/column/bg-l.png" alt="" class="bg1 bg">
                            <img src="https://www.imooc.com/static/img/column/bg-r.png" alt="" class="bg2 bg">
                            <div class="famous-word">受苦的人，没有悲观的权利。<p class="author">——尼采</p></div>
                        </div>
                                            </div>
                    <div class="art-content js-lookimg">
                        <div id="article_content">
                            <div class="cl-preview-section"><h2 id="引导语" style="font-size: 30px;">引导语</h2>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">有的面试官喜欢让同学在说完锁的原理之后，让你重写一个新的锁，要求现场在白板上写出大概的思路和代码逻辑，这种面试题目，蛮难的，我个人觉得其侧重点主要是两个部分：</p>
</div><div class="cl-preview-section"><ol>
<li style="font-size: 20px; line-height: 38px;">考察一下你对锁原理的理解是如何来的，如果你对源码没有解读过的话，只是看看网上的文章，或者背面试题，也是能够说出大概的原理，但你很难现场写出一个锁的实现代码，除非你真的看过源码，或者有和锁相关的项目经验；</li>
<li style="font-size: 20px; line-height: 38px;">我们不需要创造，我们只需要模仿 Java 锁中现有的 API 进行重写即可。</li>
</ol>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">如果你看过源码，这道题真的很简单，你可以挑选一个你熟悉的锁进行模仿。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">在锁章节中我们之前说的都是排它锁，这小节我们以共享锁作为案列，自定义一个共享锁。</p>
</div><div class="cl-preview-section"><h2 id="需求" style="font-size: 30px;">1 需求</h2>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">一般自定义锁的时候，我们都是根据需求来进行定义的，不可能凭空定义出锁来，说到共享锁，大家可能会想到很多场景，比如说对于共享资源的读锁可以是共享的，比如对于数据库链接的共享访问，比如对于 Socket 服务端的链接数是可以共享的，场景有很多，我们选择共享访问数据库链接这个场景来定义一个锁。</p>
</div><div class="cl-preview-section"><h2 id="详细设计" style="font-size: 30px;">2 详细设计</h2>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">假定(以下设想都为假定)我们的数据库是单机 mysql，只能承受 10 个链接，创建数据库链接时，我们是通过最原始 JDBC 的方式，我们用一个接口把用 JDBC 创建链接的过程进行了封装，这个接口我们命名为：创建链接接口。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">共享访问数据库链接的整体要求如下：所有请求加在一起的 mysql 链接数，最大不能超过 10（包含 10），一旦超过 10，直接报错。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">在这个背景下，我们进行了下图的设计：<br>
<img class="" src="https://img.mukewang.com/5dc386f5000160e808680456.png" data-original="//img.mukewang.com/5dc386f5000160e808680456.png" alt="图片描述"></p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">这个设计最最关键的地方，就是我们通过能否获得锁，来决定是否可以得到 mysql 链接，如果能获得锁，那么就能得到链接，否则直接报错。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">接着我们一起来看下落地的代码：</p>
</div><div class="cl-preview-section"><h3 id="定义锁">2.1 定义锁</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">首先我们需要定义一个锁出来，定义时需要有两个元素：</p>
</div><div class="cl-preview-section"><ol>
<li style="font-size: 20px; line-height: 38px;">锁的定义：同步器 Sync；</li>
<li style="font-size: 20px; line-height: 38px;">锁对外提供的加锁和解锁的方法。</li>
</ol>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">共享锁的代码实现如下：</p>
</div><div class="cl-preview-section"><pre class="  language-java"><code class="prism  language-java"><span class="token comment">// 共享不公平锁</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">ShareLock</span> <span class="token keyword">implements</span> <span class="token class-name">Serializable</span><span class="token punctuation">{</span>
	<span class="token comment">// 同步器</span>
  <span class="token keyword">private</span> <span class="token keyword">final</span> Sync sync<span class="token punctuation">;</span>
  <span class="token comment">// 用于确保不能超过最大值</span>
  <span class="token keyword">private</span> <span class="token keyword">final</span> <span class="token keyword">int</span> maxCount<span class="token punctuation">;</span>

  <span class="token comment">/**
   * 初始化时给同步器 sync 赋值
   * count 代表可以获得共享锁的最大值
   */</span>
  <span class="token keyword">public</span> <span class="token function">ShareLock</span><span class="token punctuation">(</span><span class="token keyword">int</span> count<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>sync <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Sync</span><span class="token punctuation">(</span>count<span class="token punctuation">)</span><span class="token punctuation">;</span>
    maxCount <span class="token operator">=</span> count<span class="token punctuation">;</span>
  <span class="token punctuation">}</span>

  <span class="token comment">/**
   * 获得锁
   * @return true 表示成功获得锁，false 表示失败
   */</span>
  <span class="token keyword">public</span> <span class="token keyword">boolean</span> <span class="token function">lock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token keyword">return</span> sync<span class="token punctuation">.</span><span class="token function">acquireByShared</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>

  <span class="token comment">/**
   * 释放锁
   * @return true 表示成功释放锁，false 表示失败
   */</span>
  <span class="token keyword">public</span> <span class="token keyword">boolean</span> <span class="token function">unLock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token keyword">return</span> sync<span class="token punctuation">.</span><span class="token function">releaseShared</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>  
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">从上述代码中可以看出，加锁和释放锁的实现，都依靠同步器 Sync 的底层实现。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">唯一需要注意的是，锁需要规定好 API 的规范，主要是两方面：</p>
</div><div class="cl-preview-section"><ol>
<li style="font-size: 20px; line-height: 38px;">API 需要什么，就是锁在初始化的时候，你需要传哪些参数给我，在 ShareLock 初始化时，需要传最大可共享锁的数目；</li>
<li style="font-size: 20px; line-height: 38px;">需要定义自身的能力，即定义每个方法的入参和出参。在 ShareLock 的实现中，加锁和释放锁的入参都没有，是方法里面写死的 1，表示每次方法执行，只能加锁一次或释放锁一次，出参是布尔值，true 表示加锁或释放锁成功，false 表示失败，底层使用的都是 Sync 非公平锁。</li>
</ol>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">以上这种思考方式是有方法论的，就是我们在思考一个问题时，可以从两个方面出发：API 是什么？API 有什么能力？</p>
</div><div class="cl-preview-section"><h3 id="定义同步器-sync">2.2 定义同步器 Sync</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">Sync 直接继承 AQS ，代码如下：</p>
</div><div class="cl-preview-section"><pre class="  language-java"><code class="prism  language-java"><span class="token keyword">class</span> <span class="token class-name">Sync</span> <span class="token keyword">extends</span> <span class="token class-name">AbstractQueuedSynchronizer</span> <span class="token punctuation">{</span>

  <span class="token comment">// 表示最多有 count 个共享锁可以获得</span>
  <span class="token keyword">public</span> <span class="token function">Sync</span><span class="token punctuation">(</span><span class="token keyword">int</span> count<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token function">setState</span><span class="token punctuation">(</span>count<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>

  <span class="token comment">// 获得 i 个锁</span>
  <span class="token keyword">public</span> <span class="token keyword">boolean</span> <span class="token function">acquireByShared</span><span class="token punctuation">(</span><span class="token keyword">int</span> i<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token comment">// 自旋保证 CAS 一定可以成功</span>
    <span class="token keyword">for</span><span class="token punctuation">(</span><span class="token punctuation">;</span><span class="token punctuation">;</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
      <span class="token keyword">if</span><span class="token punctuation">(</span>i<span class="token operator">&lt;=</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
      <span class="token punctuation">}</span>
      <span class="token keyword">int</span> state <span class="token operator">=</span> <span class="token function">getState</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token comment">// 如果没有锁可以获得，直接返回 false</span>
      <span class="token keyword">if</span><span class="token punctuation">(</span>state <span class="token operator">&lt;=</span><span class="token number">0</span> <span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
      <span class="token punctuation">}</span>
      <span class="token keyword">int</span> expectState <span class="token operator">=</span> state <span class="token operator">-</span> i<span class="token punctuation">;</span>
      <span class="token comment">// 如果要得到的锁不够了，直接返回 false</span>
      <span class="token keyword">if</span><span class="token punctuation">(</span>expectState <span class="token operator">&lt;</span> <span class="token number">0</span> <span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
      <span class="token punctuation">}</span>
      <span class="token comment">// CAS 尝试得到锁,CAS 成功获得锁，失败继续 for 循环</span>
      <span class="token keyword">if</span><span class="token punctuation">(</span><span class="token function">compareAndSetState</span><span class="token punctuation">(</span>state<span class="token punctuation">,</span>expectState<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
      <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>

  <span class="token comment">// 释放 i 个锁</span>
  <span class="token annotation punctuation">@Override</span>
  <span class="token keyword">protected</span> <span class="token keyword">boolean</span> <span class="token function">tryReleaseShared</span><span class="token punctuation">(</span><span class="token keyword">int</span> arg<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">for</span><span class="token punctuation">(</span><span class="token punctuation">;</span><span class="token punctuation">;</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
      <span class="token keyword">if</span><span class="token punctuation">(</span>arg<span class="token operator">&lt;=</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
      <span class="token punctuation">}</span>
      <span class="token keyword">int</span> state <span class="token operator">=</span> <span class="token function">getState</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token keyword">int</span> expectState <span class="token operator">=</span> state <span class="token operator">+</span> arg<span class="token punctuation">;</span>
      <span class="token comment">// 超过了 int 的最大值，或者 expectState 超过了我们的最大预期</span>
      <span class="token keyword">if</span><span class="token punctuation">(</span>expectState <span class="token operator">&lt;</span> <span class="token number">0</span> <span class="token operator">||</span> expectState <span class="token operator">&gt;</span> maxCount<span class="token punctuation">)</span><span class="token punctuation">{</span>
        log<span class="token punctuation">.</span><span class="token function">error</span><span class="token punctuation">(</span><span class="token string">"state 超过预期，当前 state is {},计算出的 state is {}"</span><span class="token punctuation">,</span>state
        <span class="token punctuation">,</span>expectState<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
      <span class="token punctuation">}</span>
      <span class="token keyword">if</span><span class="token punctuation">(</span><span class="token function">compareAndSetState</span><span class="token punctuation">(</span>state<span class="token punctuation">,</span> expectState<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
      <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">整个代码比较清晰，我们需要注意的是：</p>
</div><div class="cl-preview-section"><ol>
<li style="font-size: 20px; line-height: 38px;">边界的判断，比如入参是否非法，释放锁时，会不会出现预期的 state 非法等边界问题，对于此类问题我们都需要加以判断，体现出思维的严谨性；</li>
<li style="font-size: 20px; line-height: 38px;">加锁和释放锁，需要用 for 自旋 + CAS 的形式，来保证当并发加锁或释放锁时，可以重试成功。写 for 自旋时，我们需要注意在适当的时机要 return，不要造成死循环，CAS 的方法 AQS 已经提供了，不要自己写，我们自己写的 CAS 方法是无法保证原子性的。</li>
</ol>
</div><div class="cl-preview-section"><h3 id="通过能否获得锁来决定能否得到链接">2.3 通过能否获得锁来决定能否得到链接</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">锁定义好了，我们需要把锁和获取 Mysql 链接结合起来，我们写了一个 Mysql 链接的工具类，叫做 MysqlConnection，其主要负责两大功能：</p>
</div><div class="cl-preview-section"><ol>
<li style="font-size: 20px; line-height: 38px;">通过 JDBC 建立和 Mysql 的链接；</li>
<li style="font-size: 20px; line-height: 38px;">结合锁，来防止请求过大时，Mysql 的总链接数不能超过 10 个。</li>
</ol>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">首先我们看下 MysqlConnection 初始化的代码：</p>
</div><div class="cl-preview-section"><pre class="  language-java"><code class="prism  language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">MysqlConnection</span> <span class="token punctuation">{</span>
  <span class="token keyword">private</span> <span class="token keyword">final</span> ShareLock lock<span class="token punctuation">;</span>
  
  <span class="token comment">// maxConnectionSize 表示最大链接数</span>
  <span class="token keyword">public</span> <span class="token function">MysqlConnection</span><span class="token punctuation">(</span><span class="token keyword">int</span> maxConnectionSize<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    lock <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ShareLock</span><span class="token punctuation">(</span>maxConnectionSize<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">我们可以看到，在初始化时，需要制定最大的链接数是多少，然后把这个数值传递给锁，因为最大的链接数就是 ShareLock 锁的 state 值。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">接着为了完成 1，我们写了一个 private 的方法：</p>
</div><div class="cl-preview-section"><pre class="  language-java"><code class="prism  language-java"><span class="token comment">// 得到一个 mysql 链接，底层实现省略</span>
<span class="token keyword">private</span> Connection <span class="token function">getConnection</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span><span class="token punctuation">}</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">然后我们实现 2，代码如下：</p>
</div><div class="cl-preview-section"><pre class="  language-java"><code class="prism  language-java"><span class="token comment">// 对外获取 mysql 链接的接口</span>
<span class="token comment">// 这里不用try finally 的结构，获得锁实现底层不会有异常</span>
<span class="token comment">// 即使出现未知异常，也无需释放锁</span>
<span class="token keyword">public</span> Connection <span class="token function">getLimitConnection</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>lock<span class="token punctuation">.</span><span class="token function">lock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> <span class="token function">getConnection</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
  <span class="token keyword">return</span> null<span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token comment">// 对外释放 mysql 链接的接口</span>
<span class="token keyword">public</span> <span class="token keyword">boolean</span> <span class="token function">releaseLimitConnection</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">return</span> lock<span class="token punctuation">.</span><span class="token function">unLock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">逻辑也比较简单，加锁时，如果获得了锁，就能返回 Mysql 的链接，释放锁时，在链接关闭成功之后，调用 releaseLimitConnection 方法即可，此方法会把锁的 state 状态加一，表示链接被释放了。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">以上步骤，针对 Mysql 链接限制的场景锁就完成了。</p>
</div><div class="cl-preview-section"><h2 id="测试" style="font-size: 30px;">3 测试</h2>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">锁写好了，接着我们来测试一下，我们写了一个测试的 demo，代码如下：</p>
</div><div class="cl-preview-section"><pre class="  language-java"><code class="prism  language-java"><span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span>String<span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token punctuation">{</span>
  log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"模仿开始获得 mysql 链接"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  MysqlConnection mysqlConnection <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">MysqlConnection</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"初始化 Mysql 链接最大只能获取 10 个"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token keyword">for</span><span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span><span class="token number">0</span> <span class="token punctuation">;</span>i<span class="token operator">&lt;</span><span class="token number">12</span><span class="token punctuation">;</span>i<span class="token operator">++</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token keyword">if</span><span class="token punctuation">(</span>null <span class="token operator">!=</span> mysqlConnection<span class="token punctuation">.</span><span class="token function">getLimitConnection</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
      log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"获得第{}个数据库链接成功"</span><span class="token punctuation">,</span>i<span class="token operator">+</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token keyword">else</span> <span class="token punctuation">{</span>
      log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"获得第{}个数据库链接失败：数据库连接池已满"</span><span class="token punctuation">,</span>i<span class="token operator">+</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>
  log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"模仿开始释放 mysql 链接"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token keyword">for</span><span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span><span class="token number">0</span> <span class="token punctuation">;</span>i<span class="token operator">&lt;</span><span class="token number">12</span><span class="token punctuation">;</span>i<span class="token operator">++</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token keyword">if</span><span class="token punctuation">(</span>mysqlConnection<span class="token punctuation">.</span><span class="token function">releaseLimitConnection</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
      log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"释放第{}个数据库链接成功"</span><span class="token punctuation">,</span>i<span class="token operator">+</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token keyword">else</span> <span class="token punctuation">{</span>
      log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"释放第{}个数据库链接失败"</span><span class="token punctuation">,</span>i<span class="token operator">+</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>
  log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"模仿结束"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">以上代码逻辑如下：</p>
</div><div class="cl-preview-section"><ol>
<li style="font-size: 20px; line-height: 38px;">获得 Mysql 链接逻辑：for 循环获取链接，1~10 都可以获得链接，11~12 获取不到链接，因为链接被用完了；</li>
<li style="font-size: 20px; line-height: 38px;">释放锁逻辑：for 循环释放链接，1~10 都可以释放成功，11~12 释放失败。</li>
</ol>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">我们看下运行结果，如下图：<br>
<img class="" src="https://img.mukewang.com/5dc3870a0001d0bd10370766.png" data-original="//img.mukewang.com/5dc3870a0001d0bd10370766.png" alt="图片描述"></p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">从运行的结果，可以看出，我们实现的 ShareLock 锁已经完成了 Mysql 链接共享的场景了。</p>
</div><div class="cl-preview-section"><h2 id="总结" style="font-size: 30px;">4 总结</h2>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">同学们阅读到这里不知道有没有两点感受：</p>
</div><div class="cl-preview-section"><ol>
<li style="font-size: 20px; line-height: 38px;">重写锁真的很简单，最关键的是要和场景完美贴合，能满足业务场景的锁才是好锁；</li>
<li style="font-size: 20px; line-height: 38px;">锁其实只是来满足业务场景的，本质都是 AQS，所以只要 AQS 学会了，在了解清楚场景的情况下，重写锁都不难的。</li>
</ol>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">锁章节最核心的就是 AQS 源码解析的两章，只要我们把 AQS 弄懂了，其余锁的实现，只要稍微看下源码实现，几乎马上就能知道其底层实现的原理，大多数都是通过操作 state 来完成不同的场景需求，所以还是建议大家多看 AQS 源码，多 debug AQS 源码，只要 AQS 弄清楚了，锁都很简单。</p>
</div>}
                        </div>
                    </div>
                                            <!-- 买过的阅读 -->
                        <div class="art-next-prev clearfix">
                                                                                                <!-- 已买且开放 或者可以试读 -->
                                    <a href="/read/47/article/877">
                                                                    <div class="prev l clearfix">
                                        <div class="icon l">
                                            <i class="imv2-arrow3_l"></i>
                                        </div>
                                        <p>
                                            35 经验总结：各种锁在工作中使用场景和细节    
                                        </p>
                                    </div>
                                </a>
                                                                                                                            <!-- 已买且开放 或者可以试读 -->
                                    <a href="/read/47/article/879">
                                                                    <div class="next r clearfix">
                                        <p>
                                            37 ThreadPoolExecutor 源码解析 
                                        </p>
                                        <div class="icon r">
                                            <i class="imv2-arrow3_r"></i>
                                        </div>

                                    </div>
                                </a>
                                                    </div>
                                    </div>
                <div class="comments-con js-comments-con" id="coments_con">
                </div>

                
            </div>
            
            
            

        </div>
    </div>
</div>

<div class="modal modal-jiaQun-new hide" id="modal-jiaQun">
    <div class="inner" style="">
        <div class="modal-close js-close-jiaQun">
            <i class="imv2-close"></i>
        </div>
        <div class="content">
            <img src="https://img3.mukewang.com/5d634d40000119e505400602.jpg">
            <div class="right-info">
                <div class="title">
                    扫码加入慕课Java核心用户群
                </div>
                <div class="desc">
                                            <p class="mb6">验证信息：<span id="joincode">1909271435058473</span><span class="copy js-copy-joincode">复制</span></p>
                                        <p class="mb6">QQ讨论群号：906691736</p>
                                            <p>QQ群URL：<a href="https://jq.qq.com/?_wv=1027&amp;k=55RtSbJ" target="_blank">点击访问</a></p>
                                    </div>
            </div>
            <p class="tip">若遇到搜索不到QQ群或加群失败，请联系客服邮箱:kf@imooc.com</p>
        </div>
    </div>
</div>
 
<!-- 专栏介绍页专栏评价 -->

<!-- 专栏介绍页底部三条评价 -->

<!-- 专栏阅读页弹层目录和介绍页页面目录 -->

<!-- 专栏阅读页发布回复 -->

<!-- 专栏阅读页发布评论 -->

<!-- 专栏阅读页底部评论 -->

<!-- 专栏阅读 单个 评论 -->

<!-- 新增回复和展开三条以外回复 -->

<!-- 立即订阅的弹窗 -->












</div></body></html>